import express from "express";
import { createServer } from "http";
import { Server } from "socket.io";

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, { cors:true });

const userMap={}
const chatroom=io.of("chatroom")
chatroom.on("connection", (socket) => {
    socket.on("disconnect", () => {
        delete userMap[socket.id]
        chatroom.emit("updateUser",userMap)
    });
    socket.on("init",(initData)=>{
        const {username}=initData
        userMap[socket.id]=username
        chatroom.emit("updateUser",userMap)
    })
    socket.on("input",(chatText)=>{
        const {id}=socket
        chatroom.emit("pushTextEveryone",{chatText,id})
    })
});

const userMap2={}
const videoroom=io.of("videoroom")
videoroom.on("connection", (socket) => {
    socket.on("disconnect", () => {
        delete userMap2[socket.id]
        videoroom.emit("updateUser",userMap2)
    });
    socket.on("init",(initData)=>{
        const {username}=initData
        userMap2[socket.id]=username
        videoroom.emit("updateUser",userMap2)
    })
    socket.on("sendOffer",(description)=>{
        socket.broadcast.emit("receiverOffer",description)
    })
    socket.on("sendAnswer",(description)=>{
        socket.broadcast.emit("receiverAnswer",description)
    })
    socket.on("hostSendCandidate",(candidate)=>{
        socket.broadcast.emit("audienceReceiverCandidate",candidate)
    })
    socket.on("audienceSendCandidate",(candidate)=>{
        socket.broadcast.emit("hostReceiverCandidate",candidate)
    })
});

const userMap3={}
const shareDoc=io.of("shareDoc")
shareDoc.on("connection", (socket) => {
    socket.on("disconnect", () => {
        delete userMap3[socket.id]
        shareDoc.emit("updateUser",userMap3)
    });
    socket.on("init",(initData)=>{
        const {username}=initData
        userMap3[socket.id]=username
        shareDoc.emit("updateUser",userMap3)
    })
    socket.on("input",(delta)=>{
        const {id}=socket
        shareDoc.emit("pushDeltaEveryone",{delta,id})
    })
});

const userMap4={}
const shareBoard=io.of("shareBoard")
shareBoard.on("connection", (socket) => {
    socket.on("disconnect", () => {
        delete userMap4[socket.id]
        shareBoard.emit("updateUser",userMap4)
    });
    socket.on("init",(initData)=>{
        const {username}=initData
        userMap4[socket.id]=username
        shareBoard.emit("updateUser",userMap4)
    })
    socket.on("move",({lastX,lastY,offsetX,offsetY})=>{
        const {id}=socket
        shareBoard.emit("pushPointEveryone",{lastX,lastY,offsetX,offsetY,id})
    })
});


httpServer.listen(3333,()=>{
    console.log("服务在3333端口运行")
});